#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/ledc.h"

// PWM 配置
#define LED_PIN         13      // GPIO13 控制 LED
#define LEDC_CHANNEL    LEDC_CHANNEL_0
#define LEDC_MODE       LEDC_LOW_SPEED_MODE
#define LEDC_DUTY_RES   LEDC_TIMER_8_BIT  // 8 位分辨率（0-255）
#define LEDC_FREQUENCY  5000    // 5kHz PWM 频率

void app_main()
{
    // 1. 配置 PWM 定时器
    ledc_timer_config_t timer_cfg = {
        .speed_mode = LEDC_MODE,
        .duty_resolution = LEDC_DUTY_RES,
        .timer_num = LEDC_TIMER_0,
        .freq_hz = LEDC_FREQUENCY,
        .clk_cfg = LEDC_AUTO_CLK
    };
    ledc_timer_config(&timer_cfg);

    // 2. 配置 PWM 通道
    ledc_channel_config_t channel_cfg = {
        .gpio_num = LED_PIN,
        .speed_mode = LEDC_MODE,
        .channel = LEDC_CHANNEL,
        .timer_sel = LEDC_TIMER_0,
        .duty = 0,  // 初始占空比 0（灯灭）
        .hpoint = 0
    };
    ledc_channel_config(&channel_cfg);

    // 3. 渐变调光演示
    while (1) {
        // 从暗到亮（占空比 0→255）
        for (int duty = 0; duty < 256; duty++) {
            ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, duty);
            ledc_update_duty(LEDC_MODE, LEDC_CHANNEL);
            vTaskDelay(10 / portTICK_PERIOD_MS);
        }

        // 从亮到暗（占空比 255→0）
        for (int duty = 255; duty >= 0; duty--) {
            ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, duty);
            ledc_update_duty(LEDC_MODE, LEDC_CHANNEL);
            vTaskDelay(10 / portTICK_PERIOD_MS);
        }
    }
}